import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/customwidget/event_widget/event.dart';
import 'package:flutter_app/util/random.dart';

///事件总线通常实现了订阅者模式，订阅者模式包含发布者和订阅者两种角色，可以通过事件总线来触发事件和监听事件
///
class EventBusPage extends StatefulWidget {
  final String? title;

  EventBusPage({this.title}) : super();

  @override
  State<StatefulWidget> createState() {
    return _EventState();
  }
}

const String EVENT_CHANGE_COLOR = "event_change_color";

class _EventState extends State<EventBusPage> {
  Color _primaryColor = Colors.blue;
  bool _isSubscription = false; //是否订阅
  @override
  void initState() {
    super.initState();
    initEvent();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title ?? ""),
        backgroundColor: _primaryColor,
      ),
      body: Container(
        padding: const EdgeInsets.all(10),
        child: ListView(
          scrollDirection: Axis.vertical, // 水平listView
          children: [
            ButtonBar(
              alignment: MainAxisAlignment.start, //布局方向，默认MainAxisAlignment.end
              mainAxisSize: MainAxisSize.min, //主轴大小，默认MainAxisSize.max
              children: [
                TextButton(
                    child: Text("改变标题背景色"),
                    onPressed: () => {
                          XEvent.post(
                              EVENT_CHANGE_COLOR, RandomUtils.getRandomColor())
                        }),
                TextButton(
                  child: Text(_isSubscription ? '取消订阅' : "订阅"),
                  onPressed: switchEvent,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

//启用订阅
  void initEvent() {
    if (!_isSubscription) {
      //未订阅
      XEvent.on<Color>(EVENT_CHANGE_COLOR, (color) {
        setState(() {
          _primaryColor = color;
        });
      });
      setState(() {
        _isSubscription = true;
      });
    }
  }

//切换订阅
  void switchEvent() {
    if (_isSubscription) {
      XEvent.cancelAll(EVENT_CHANGE_COLOR);
      setState(() {
        _isSubscription = false;
      });
    } else {
      initEvent();
    }
  }

  @override
  void dispose() {
    super.dispose();
    //取消订阅
    XEvent.cancelAll(EVENT_CHANGE_COLOR);
  }
}
